package chapter12;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.*;
import java.nio.file.*;
import java.util.List;

/**
 * @author yuhui
 * descriptions:
 * @create 2024 - 11 - 21 11:23 上午
 */
public class VideoUtil {
    /**
     * 对我们的数据进行清洗的工作，
     * 数据切割，如果长度小于9 直接丢掉
     * 视频类别中间空格 去掉
     * 关联视频，使用 &  进行分割
     *
     * @param line
     * @return FM1KUDE3C3k  renetto	736	News & Politics	1063	9062	4.57	525	488	LnMvSxl0o0A&IKMtzNuKQso&Bq8ubu7WHkY&Su0VTfwia1w&0SNRfquDfZs&C72NVoPsRGw
     */
    public static String washDatas(String line) {
        if (null == line || "".equals(line)) {
            return null;
        }

        if (line.length() < 20) {
            return null;
        }

        //判断数据的长度，如果小于9，直接丢掉
        String[] split = line.split("\t");
        if (split.length < 9) {
            return null;
        }
        //将视频类别空格进行去掉
        split[3] = split[3].replace(" ", "");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            if (i < 9) {
                //这里面是前面八个字段
                builder.append(split[i]).append("\t");
            } else if (i >= 9 && i < split.length - 1) {
                builder.append(split[i]).append("&");
            } else if (i == split.length - 1) {
                builder.append(split[i]);
            }
        }
        return builder.toString();
    }

    public static void main(String[] args) {

        String inputFilePath = "/Users/yuhui/Desktop/11/3.txt";
        String outputFilePath = "/Users/yuhui/Desktop/11/output3.txt";

        try {
            // 读取文件内容
            List<String> lines = Files.readAllLines(Paths.get(inputFilePath));

            // 处理文件内容并保存结果
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
                for (String line : lines) {
                    String processedLine = washDatas(line);
                    if (processedLine != null) { // 检查processedLine是否为null
                        writer.write(processedLine);
                        writer.newLine();  // 换行
                    } else {
                        // 可选：记录跳过的行或执行其他操作
                        System.out.println("Skipped a line due to invalid data.");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("Failed to write to the output file.");
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Failed to read the input file.");
        }

    }
}
